package com.kzw.oa.system.web;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.kzw.core.util.XML2JSON;
import com.kzw.core.util.web.ResponseUtils;
import com.kzw.misc.utils.AppUtil;
import com.kzw.misc.utils.ContextUtil;
import com.kzw.oa.system.model.AppRole;

/**
 * @description 显示系统左边的功能菜单
 */
@Controller
@RequestMapping("/menu")
public class MenuAction {

	private Log logger = LogFactory.getLog(getClass());

	/**
	 * 返回当前用户左树的菜单
	 */
	@RequestMapping("panelTree")
	public void panelTree(String topMenuId, HttpServletRequest request, HttpServletResponse response) {

		String isReload = request.getParameter("isReload");
		// reload the menu
		if ("true".equals(isReload)) {
			AppUtil.reloadMenu();
		}

		topMenuId = topMenuId.replace("Mod_", "");
		Document doc = getCurDocument(topMenuId);

		StringBuffer sb = new StringBuffer("[");
		if (doc != null) {
			Element root = doc.getRootElement();
			List<?> els = root.elements();

			for (int i = 0; i < els.size(); i++) {
				Element el = (Element) els.get(i);

				Attribute id = el.attribute("id");
				Attribute text = el.attribute("text");
				Attribute iconCls = el.attribute("iconCls");

				String json = XML2JSON.parse(getModelXml(doc, id.getValue()));
				json = json.replace("Items", "children");
				json = json.replace("Item", "children");

				sb.append("{\"id\":\"").append(id == null ? "" : id.getValue()).append("\",");
				sb.append("\"text\":\"").append(text == null ? "" : text.getValue()).append("\",");
				sb.append("\"iconCls\":\"").append(iconCls == null ? "" : iconCls.getValue()).append("\",");
				sb.append("\"subXml\":").append(json).append("},");
			}
			if (els.size() > 0) {
				sb.deleteCharAt(sb.length() - 1);
			}
		}
		sb.append("]");

		ResponseUtils.renderJson(response, sb.toString());
	}

	/**
	 * 返回某个模板的XML菜单
	 * 
	 * @param doc
	 * @param modelId
	 * @return
	 */
	protected String getModelXml(Document doc, String modelId) {
		StringBuffer sb = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r");
		Element el = doc.getRootElement();
		List nodes = el.selectNodes("/Menus/Items[@id='" + modelId + "']/*");

		sb.append("<Menus>\r");
		for (int i = 0; i < nodes.size(); i++) {
			Node node = (Node) nodes.get(i);
			sb.append(node.asXML());
		}
		sb.append("\r</Menus>\r");

		return sb.toString();
	}

	/**
	 * 根据权限获取当前用户的菜单
	 * 
	 * @return
	 */
	private Document getCurDocument(String topMenuId) {
		Document doc = getModuleDocument(topMenuId);
		Set<String> rights = ContextUtil.getCurrentUser().getRights();

		if (rights.contains(AppRole.SUPER_RIGHTS)) {// 具有超级管理权限
			return doc;
		}

		Document newDoc = DocumentHelper.createDocument();
		Element root = newDoc.addElement("Menus");

		createSubMenus(rights, doc.getRootElement(), root);

		if (logger.isDebugEnabled()) {
			logger.debug("XML:" + newDoc.asXML());
		}

		return newDoc;

	}

	private Document getModuleDocument(String topMenuId) {
		if (StringUtils.isEmpty(topMenuId)) {
			topMenuId = "oa";
		}

		Document doc = AppUtil.getItemsMenus().get(topMenuId.toLowerCase());

		return doc;

	}

	private void createSubMenus(Set<String> rights, Element curNodes, Element newCurNodes) {
		List els = curNodes.elements();
		if (els.size() == 0)
			return;

		for (int i = 0; i < els.size(); i++) {
			Element el = (Element) els.get(i);
			String id = el.attributeValue("id");
			if (id != null) {
				if (rights.contains(id)) {
					Element newNodes = newCurNodes.addElement(el.getName());
					Iterator<Attribute> it = el.attributeIterator();

					while (it.hasNext()) {
						Attribute at = it.next();
						newNodes.addAttribute(at.getName(), at.getValue());
					}
					createSubMenus(rights, el, newNodes);
				}
			}
		}
	}

}
